# plate_consumer/src/models.py
from sqlalchemy import create_engine, Column, Integer, String, DateTime, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime

Base = declarative_base()


class DetectionResult(Base):
    __tablename__ = 'detection_result'

    id = Column(Integer, primary_key=True)
    plate_number = Column(String(20), nullable=False)
    entry_time = Column(DateTime, default=datetime.now)
    exit_time = Column(DateTime)
    confidence = Column(Float)
    amount_due = Column(Integer, default=0)

    # 索引配置（通过事件监听实现）
    __table_args__ = (
        {'mysql_charset': 'utf8mb4', 'mysql_engine': 'InnoDB'}
    )

    def to_dict(self):
        return {
            "id": self.id,
            "plate_number": self.plate_number,
            "entry_time": self.entry_time.isoformat() if self.entry_time else None,
            "exit_time": self.exit_time.isoformat() if self.exit_time else None,
            "confidence": self.confidence,
            "amount_due": self.amount_due
        }
def init_db(engine):
    Base.metadata.create_all(bind=engine)
